export const mergeData = (addList,chooseArr)=>{
    const totalSpan = chooseArr.reduce((sum, index) => sum + addList[index].span, 0);
    const firstIndex = Math.min(...chooseArr);
    addList[firstIndex].span = totalSpan;
    addList[firstIndex].checked = false;
    const sortedIndices = [...chooseArr]
            .filter(index => index !== firstIndex)
            .sort((a, b) => b - a);

    for (let i = 0; i < sortedIndices.length; i++) {
        addList.splice(sortedIndices[i], 1);
    }
    addList.forEach((item,index) => {
        item.total = addList.length
        item.sort = index
    })
    return addList
}

export const mergeData2 = (addList,chooseArr)=>{
    const crr = addList.filter(item => item.checked)
    const ts = crr.reduce((sum, item) => sum + item.span, 0)
    if(ts % 2 === 1){
        return '合并后的格子必须是完整的矩形'
    }
    const srr = [...chooseArr].sort((a, b) => a - b)
    const frr = addList.slice(0, srr[0])
    const ft = frr.reduce((sum, item) => sum + item.span, 0)
    if(ft % 2 === 1){
        return '合并后的格子必须是完整的矩形'
    }
    const totalSpan = chooseArr.reduce((sum, index) => sum + addList[index].span, 0);
    const firstIndex = Math.min(...chooseArr);
    addList[firstIndex].span = totalSpan;
    addList[firstIndex].checked = false;
    const sortedIndices = [...chooseArr]
            .filter(index => index !== firstIndex)
            .sort((a, b) => b - a);

    for (let i = 0; i < sortedIndices.length; i++) {
        addList.splice(sortedIndices[i], 1);
    }
    addList.forEach((item,index) => {
        item.sort = index
    })
    return addList
}

export const splitData = (addList,chooseArr)=>{
    const selectedIndex = chooseArr.value[0];
    const selectedCell = addList.value[selectedIndex];
    const span = selectedCell.span;
    const newList = [];
    let newSortIndex = 0;
    addList.value.forEach((item, index) => {
        if (index === selectedIndex) {
            for (let i = 0; i < span; i++) {
                newList.push({
                    ...item,
                    span: 1,
                    sort: newSortIndex++,
                    checked: false
                });
            }
        } else {
            newList.push({
                ...item,
                sort: newSortIndex++,
                checked: false
            });
        }
    })
    return newList
}